////////////////////////////////////////////////////////////////////////////////////////////////////

#include "CLevelEditor.h"
#include "CPlaneCamera.h"
#include "CUserInterface.h"
#include "IDoUndoCommand.h"
#include "CMultiCommand.h"
#include "CEmptyCommand.h"
#include "CMultiCommand.h"
#include "CMoveCommand.h"
#include "CCubeSceneNode.h"
#include "CGUITreeCtrl.h"
#include "IFileSystem.h"
#include "IXMLWriter.h"
#include "IGUIEnvironment.h"
#include "IGUIListBox.h"
#include "IWriteFile.h"
#include "IFileList.h"
#include "ISceneManager.h"
#include "FpsSceneManager.h"
#include "ICameraSceneNode.h"
#include "IrrlichtDevice.h"
#include "Utils\Utils.h"
#include "CGameObject.h"
#include "IReadFile.h"
#include <windows.h>
#include <time.h>

#ifdef PFEXPORT
#include "IlluminationMap\PFExporter.h"
#endif


//#include "FpsMemoryWriteFile.h"
extern CUserInterface* ui;
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
s32 CLevelEditor::loadProcessXML(IXMLReader* xml, const irr::core::stringc& fileName)
{
	u32 versionMajor= 0;
	u32 versionMinor= 0;
	u32 versionBuild= 0;

	int oldCamera = 0;
	vector3df cpos = vector3df( 0.0f, 100.0f, 100.0f );
	vector3df tpos = vector3df(0.0f, 0.0f, 0.0f);

	while(xml->read())
	{
		io::IAttributes* attributes = NULL;

		if (core::stringw(L"irr_version") == xml->getNodeName())
		{
			bool bEndAttr = false;
			
			while(xml->read() && !bEndAttr)
			{
				const wchar_t* name = xml->getNodeName();

				switch(xml->getNodeType())
				{
				case io::EXN_ELEMENT_END:
					if (core::stringw(L"irr_version")==name)
						bEndAttr = true;
					break;

				case io::EXN_ELEMENT:
					// read attributes
					attributes = g->device->getFileSystem()->createEmptyAttributes();
					attributes->read(xml, true);

					versionMajor = attributes->getAttributeAsInt("Major");
					versionMinor = attributes->getAttributeAsInt("Minor");
					versionBuild = attributes->getAttributeAsInt("Build");
							
					//if ((versionMajor > g->m_versionMajor) || 
					//	(versionMinor > g->m_versionMinor) ||
					//	(versionBuild > g->m_versionBuild))
					//{
					//	//trying to load a newer level with an older version
					//	return 1;
					//}
					break;
				}

				if (bEndAttr)
					break;
			}

			continue;
		}

		if (core::stringw(L"irr_camera") == xml->getNodeName())
		{
			bool bEndAttr = false;
			
			while(xml->read() && !bEndAttr)
			{
				const wchar_t* name = xml->getNodeName();

				switch(xml->getNodeType())
				{
				case io::EXN_ELEMENT_END:
					if (core::stringw(L"irr_camera")==name)
						bEndAttr = true;
					break;

				case io::EXN_ELEMENT:
					// read attributes
					attributes = g->device->getFileSystem()->createEmptyAttributes();
					attributes->read(xml, true);

					oldCamera = attributes->getAttributeAsInt("type");
					cpos = attributes->getAttributeAsVector3d("Position");
					tpos = attributes->getAttributeAsVector3d("Target");

					g->setActiveCamera(oldCamera);
					g->sceneManager->getActiveCamera()->setPosition(cpos);
					g->sceneManager->getActiveCamera()->setTarget(cpos + ((tpos - cpos).normalize()) * 200);

					if(oldCamera == CAMERA_XY)
					{
						CPlaneCameraAnimator* anim =
							(CPlaneCameraAnimator*)*g->sceneManager->getActiveCamera()->getAnimators().begin();

						anim->setZoom();
					}

					break;
				}

				if (bEndAttr)
					break;
			}

			continue;
		}

		if (core::stringw(L"irr_strings") == xml->getNodeName())
		{
			if (xml->getNodeType() != EXN_ELEMENT_END)
			{
				stringc fileName = xml->getAttributeValue(L"file");
				bool bFound = false;
				for(int i=0;i<m_stringsFiles.size();i++)
				{
					if( fileName ==  m_stringsFiles[i] )
					{
						bFound = true;
						break;
					}
				}
				if( !bFound )
				{
					m_stringsFiles.push_back(fileName);

					SGameList list;

					if( fileName.size()!=0 )
					{
						if ( !LoadListFromFile(fileName, list))
						{
							g->guienv->addMessageBox(L"Error!", (stringw(L"Cannot load strings '") + stringw(fileName.c_str()).c_str() + stringw(L"'!")).c_str(), true);
						}
						else
						{
							m_GameLists.push_back(list);
							if( fileName.find("main.xml") !=-1)
							{
								m_stringsList = m_GameLists.getLast();
							}
						}
					}
				}
			}

			continue;
		}

		if (core::stringw(L"irr_music") == xml->getNodeName())
		{
			if (xml->getNodeType() != EXN_ELEMENT_END)
			{
				stringc fileName = xml->getAttributeValue(L"file");
				m_musicFile = fileName;
			}

			continue;
		}

		if (core::stringw(L"link") == xml->getNodeName())
		{
			if (xml->getNodeType() != EXN_ELEMENT_END)
			{
				stringc fileName = xml->getAttributeValue(L"fileName");

				IReadFile* file = g->device->getFileSystem()->createAndOpenFile( fileName.c_str() );
				if (!file)
				{
					g->guienv->addMessageBox(L"Error!", (stringw(L"Cannot load '") + stringw(fileName.c_str()).c_str() + stringw(L"'!")).c_str(), true);
				}
				else
				{
					long len	 = file->getSize();	
					char* buffer = new char[len];	
					file->read(buffer , len );
					file->drop();

					IReadFile* mFile = g->device->getFileSystem()->createMemoryReadFile( buffer , len, fileName.c_str() ,  true );
					IXMLReader* _xml = g->device->getFileSystem()->createXMLReader(mFile);
					//IXMLReader* _xml = g->device->getFileSystem()->createXMLReader(fileName.c_str());
					if (!_xml)
					{
						g->guienv->addMessageBox(L"Error!", (stringw(L"Cannot load '") + stringw(fileName.c_str()).c_str() + stringw(L"'!")).c_str(), true);
					}
					else
					{
						loadProcessXML(_xml, fileName);
						_xml->drop();
					}
				}
			}

			continue;
		}

		if (core::stringw(L"node") != xml->getNodeName())
		{
			continue;
		}

		// find node type and create it
		core::stringc attrName = xml->getAttributeValue(L"type");

		// read attributes
		while(xml->read())
		{
			bool endreached = false;

			switch (xml->getNodeType())
			{
			case io::EXN_ELEMENT_END:
				if ((core::stringw(L"node") == xml->getNodeName()) ||
					(core::stringw(L"irr_scene") == xml->getNodeName()))
				{
					endreached = true;
				}
				break;

			case io::EXN_ELEMENT:
				if (core::stringw(L"attributes")==xml->getNodeName())
				{
					// read attributes
					attributes = g->device->getFileSystem()->createEmptyAttributes();
					attributes->read(xml, true);
				}
				else if (core::stringw(L"userData")==xml->getNodeName())
				{
					bool bEndUserData = false;
					while(xml->read() && !bEndUserData)
					{
						const wchar_t* name = xml->getNodeName();

						switch(xml->getNodeType())
						{
						case io::EXN_ELEMENT_END:
							if (core::stringw(L"userData")==name)
								bEndUserData = true;
							break;

						case io::EXN_ELEMENT:
							if (core::stringw(L"attributes")==name)
							{
								// read user data from attribute list
								io::IAttributes* userData = g->device->getFileSystem()->createEmptyAttributes();
								userData->read(xml);

								stringc gameType = userData->getAttributeAsString("!GameType");

								TreeNode* pParentTreeNode = ui->m_sceneGraphTree->FindNode(userData->getAttributeAsInt("#ParentID"));
								ui->m_sceneGraphTree->SetSelected(pParentTreeNode);
								
								CSceneObject* pLastObj = 0;
								
								int oldID = attributes->getAttributeAsInt("Id");
								for (u32 i=0; i < m_SceneObjects.size(); i++)
								{
									if (m_SceneObjects[i]->m_SceneNode->getID() == oldID)
									{
										stringw strError = L"ID '";
										strError += oldID;
										strError += L"' already exists!!!";
										g->guienv->addMessageBox(L"Error!", strError.c_str(), true);
										break;
									}
								}

								for (u32 i=0; i < m_GameObjects.size(); i++)
								{
									if (gameType == m_GameObjects[i]->m_Attributes->getAttributeAsString("!GameType"))
									{
										pLastObj = createGameObject(i , oldID , false , true);
										break;
									}
								}

								if (pLastObj)
								{
									//NS temp to get old version cinematic files
									if (userData->getAttributeAsString("!GameType") == "Cinematic")
									{
										stringc sceneFileNameNoExt = m_SceneFileName;
										int idx = m_SceneFileName.findLast('.');
										if (idx != -1)
										{
											sceneFileNameNoExt = m_SceneFileName.subString(0, idx);
										}

										stringc cinematicFile = ".\\cinematics\\";
										cinematicFile += sceneFileNameNoExt;
										cinematicFile += "_";
										cinematicFile += pLastObj->m_SceneNode->getID();
										cinematicFile += "_";
										cinematicFile += "cinematic.cff";

										if (userData->findAttribute("!ScriptFile") > -1 )
										{
											rename(userData->getAttributeAsString("!ScriptFile").c_str(), cinematicFile.c_str());
										}
									}
									//--------------------------------------------------------------------

									copyAttributes(pLastObj->m_UserData, userData, -1, true);
									userData->drop();
										
									pLastObj->InitAttributes( false );

									pLastObj->m_SceneNode->deserializeAttributes(attributes);

									//set parent for camera control point
									if (pLastObj->m_UserData->getAttributeAsString("!GameType") == "CamCtrlPoint" )
									{			
										int CAID = pLastObj->m_UserData->getAttributeAsInt("!^Owner^CameraArea");
										CSceneObject* ca_obj = getSceneObjectFromID(CAID);						
										if(ca_obj!=0 && ca_obj->m_SceneNode!=0 && ca_obj->m_SceneNode->getParent())
										{
											ca_obj->m_SceneNode->getParent()->addChild(pLastObj->m_SceneNode);											
										}
									}

									// update position from absolute matrix - fix for geometry changes
									vector3df absPos = attributes->getAttributeAsMatrix("AbsoluteTransformation").getTranslation();
									irr::scene::ISceneNode* pParent = pLastObj->m_SceneNode->getParent();
									UpdateNodeAbsPosition( pParent );
									int id = pLastObj->m_SceneNode->getID();
									pLastObj->m_SceneNode->setPosition(absPos - pParent->getAbsolutePosition());
									pLastObj->m_SceneNode->updateAbsolutePosition();

									if (pLastObj->m_UserData->getAttributeAsString("!GameType") == "Geometry")
									{
										loadRoomLinks(pLastObj, attributes);

										
										irr::core::stringc illumapName = fileName;
										int _size = fileName.size();
										illumapName = illumapName.subString(0,_size-4);
										//illumapName += "_";
										//illumapName += pLastObj->m_UserData->getAttributeAsString("Name");
										illumapName += ".light";
										PFExporter::AddRoomMap(pLastObj->m_SceneNode, illumapName.c_str());
									}

									bool bIsVisible = pLastObj->m_SceneNode->isVisible();
									pLastObj->m_SceneNode->OnAnimate(0);
									pLastObj->m_SceneNode->setVisible(bIsVisible);

									pLastObj->ProcessAttributes();
																		
									TreeNode* pTreeNode = ui->m_sceneGraphTree->FindNode(pLastObj->m_SceneNode->getID());
									
									pTreeNode->Checked = pLastObj->m_SceneNode->isVisible();
									pTreeNode->Text = stringw(pLastObj->m_SceneNode->getID()) + " - " + pLastObj->m_UserData->getAttributeAsStringW("Name");
									pTreeNode->LowerText = pTreeNode->Text;
									pTreeNode->LowerText.make_lower();
									
									//if(!pLastObj->m_SceneNode->isVisible())								
									//ui->setSceneNodeVisible(pLastObj->m_SceneNode->getID(), pLastObj->m_SceneNode->isVisible());
								}
								else
								{
									DEBUG_OUT("Object of type %s was not created this step !!!" , gameType);
								}

								
								m_SaveLoadProgress ++;
									
								//g->run();													
							}
							break;

						default:
							break;
						}
					}
				}
				break;

			default:
				break;
			}

			if (endreached)
				break;
		}
	}	

	return 0;
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
s32 CLevelEditor::loadScene(stringc sceneName)
{
	u32 i;		

	setSelectedNode(0);
	m_selection.clear();
	m_bModified = false;
	m_LastFocusedNode = 0;
	
	for (i = 0; i < m_SceneObjects.size(); i ++)
		if (m_SceneObjects[i])
			delete m_SceneObjects[i];

	m_lastUniqueId = 0;

	m_SceneObjects.clear();
	//m_TreeList.clear();
	ui->m_sceneGraphTree->Clear();
	ui->m_SceneGraphPropertiesVisibleList->clear();
	ui->m_SceneGraphPropertiesInvisibleList->clear();
	ui->m_SceneGraphPropertiesLockedList->clear();
	g->sceneManager->clear();
	ReAddEffectsToScene();

	m_SaveLoadProgressDraw = true;
	m_SaveLoadProgress = 0;

	PFExporter::ClearRoomMaps();

//	if (g->sceneManager->loadScene(sceneName.c_str(), this))
//		setSceneFileName(sceneName);		


	IReadFile* file = g->device->getFileSystem()->createAndOpenFile( sceneName.c_str() );
	long len	 = file->getSize();	
	char* buffer = new char[len];	
	file->read(buffer , len );
	file->drop();

	IReadFile* mFile = g->device->getFileSystem()->createMemoryReadFile( buffer , len,  sceneName.c_str() ,  true );	
	IXMLReader* xml = g->device->getFileSystem()->createXMLReader(mFile);
	

	if (!xml)
		return -1;

	setSceneFileName(ui->m_sceneName);

	g->initScene();
	//g->camera[MAYA_CAMERA]->setFarValue(m_mayaCameraFar);		

	m_stringsFiles.clear();
	loadProcessXML(xml, sceneName);

	xml->drop();

	//load sound list
	irr::core::stringc soundXML = "..\\..\\..\\src\\AutoGenerated\\VoxSounds.xml";
	SGameList soundList;
	if (LoadListFromFile(soundXML, soundList))						
	{
		m_GameLists.push_back(soundList);
	}
	
	// recreate every thing here ....

	m_SaveLoadProgressDraw = false;

	for (u32 i = 0; i < m_HistoryCommands.size(); ++i)
	{
		m_HistoryCommands[i]->drop();
	}
	m_HistoryCommands.clear();
	m_LastCommand = 0;
	ui->m_HistoryList->clear();

	m_nHistoryCommands = 0;
	AddCommand(new CEmptyCommand);

	for (u32 i=0; i < m_SceneObjects.size(); i++)
	{
		TreeNode* pNode = ui->m_sceneGraphTree->FindNode(m_SceneObjects[i]->m_SceneNode->getID());
		pNode->Open = false;
	}

	((CGUITreeCtrl*)ui->m_sceneGraphTree)->ScrollBarV->setPos(0);

	RecalculateCollisions();
	
	//force init anim applyed
	//for(int kk=0; kk<2; kk++)//by dai_yx
	//{			
	//	g->sceneManager->update( 50 , true );
	//	int time = ( (CFpsSceneManager*)g->sceneManager )->getSceneTime();
	//	for (u32 i = 0; i < m_SceneObjects.size(); ++i)
	//	{
	//		CSceneObject* obj = m_SceneObjects[i];
	//		if (obj && obj->HasAnim())
	//		{
	//			obj->m_SceneNode->OnAnimate( time );
	//			//obj->UpdateAnim();
	//		}
	//	}
	//}
	
	return 0 ;// no error
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void CLevelEditor::saveSceneObject(CSceneObject* pObj, IXMLWriter* xml)
{
	ESCENE_NODE_TYPE nodeType = pObj->m_SceneNode->getType();
	
	//if (isUserDefinedMesh(m_SceneObjects[i]->m_SceneNode)) continue;

	xml->writeElement(L"node", false, L"type", core::stringw(g->sceneManager->getSceneNodeTypeName(nodeType)).c_str());
	xml->writeLineBreak();
	xml->writeLineBreak();

	// write attributes

	io::IAttributes* attr = g->device->getFileSystem()->createEmptyAttributes();
	//m_SceneObjects[i]->m_SceneNode->serializeAttributes(attr);

	if (pObj->m_UserData->getAttributeAsString("!GameType") == "Geometry")
	{
		saveRoomLinks(pObj, attr);
	}

	attr->addInt("Id", pObj->m_SceneNode->getID());
	attr->addVector3d("Position", pObj->m_SceneNode->getPosition());
	attr->addQuaternion("Rotation", pObj->m_SceneNode->getRotation());
	attr->addVector3d("Scale", pObj->m_SceneNode->getScale());
	attr->addMatrix("AbsoluteTransformation", pObj->m_SceneNode->getAbsoluteTransformation());
	attr->addBool("Visible", pObj->m_SceneNode->isVisible());
	//attr->addVector3d("MinEdge", pObj->m_box.MinEdge);
	//attr->addVector3d("MaxEdge", pObj->m_box.MaxEdge);

	if (pObj->m_SceneNode->getType() == ESNT_CUBE )
	{
		attr->addFloat("Size", 100.0f);
	}

	if (attr->getAttributeCount() != 0)
	{
		attr->write(xml);
		xml->writeLineBreak();
	}
	
	attr->drop();

	// write user data

	io::IAttributes* userData = this->createUserData(pObj->m_SceneNode);

	if (userData)
	{
		const wchar_t* userDataElement = L"userData";

		xml->writeLineBreak();
		xml->writeElement(userDataElement);
		xml->writeLineBreak();

		userData->write(xml);

		xml->writeClosingTag(userDataElement);
		xml->writeLineBreak();
		xml->writeLineBreak();

		userData->drop();
	}

	xml->writeClosingTag(L"node");
	xml->writeLineBreak();
	xml->writeLineBreak();
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void CLevelEditor::saveTreeNode(TreeNode* treeNode, IXMLWriter* xml, bool bAutoSave)
{
	if (!treeNode) return;

	IXMLWriter* _xml = xml;
	//CMemoryWriteFile* file = 0 ;
	CSceneObject* sceneObject = getSceneObjectFromID(treeNode->ID);
	if (sceneObject)
	{
		stringc objType = sceneObject->m_UserData->getAttributeAsString("!GameType");

		//write in new file
		if (objType == "Geometry"/* || objType == "Group"*/)
		{
			int idx = m_SceneFileName.findLast('.');
			stringc newXmlName = "_";
			newXmlName += treeNode->ID;
			newXmlName += "_";
			newXmlName += sceneObject->m_UserData->getAttributeAsString("Name");
			newXmlName.replace('/','_'); 
			if (idx != -1)
			{
				newXmlName = m_SceneFileName.subString(0, idx) + newXmlName + m_SceneFileName.subString(idx, m_SceneFileName.size() - idx);
			}
			else
			{
				newXmlName = m_SceneFileName + newXmlName;
			}

			if (bAutoSave)
			{
				newXmlName += ".autosave";
			}

			//s32 size = 65536;
			//void* memory = new c8[size];

			//file = new CMemoryWriteFile(memory, size, newXmlName.c_str(), true);


			_xml = g->device->getFileSystem()->createXMLWriter(newXmlName.c_str());

			_xml->writeXMLHeader();
			_xml->writeLineBreak();

			//write link in parent file
			xml->writeElement(L"link", true, L"fileName", stringw(newXmlName.c_str()).c_str());
			xml->writeLineBreak();
			xml->writeLineBreak();
		}

		saveSceneObject(sceneObject, _xml);
	}

	saveTreeNode(treeNode->Child, _xml, bAutoSave);

	if (xml != _xml) 
	{	
		_xml->drop();
		
		//if (file)
		//file->drop();
	}

	saveTreeNode(treeNode->Sibling, xml, bAutoSave);
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void CLevelEditor::saveScene(bool bAutoSave)
{
	g->device->getFileSystem()->changeWorkingDirectoryTo(m_SceneFilePath.c_str());
	vector3df cpos = g->sceneManager->getActiveCamera()->getPosition();
	vector3df tpos = g->sceneManager->getActiveCamera()->getTarget();
	//vector3df cscale = g->sceneManager->getActiveCamera()->getScale();
	//quaternion crot = g->sceneManager->getActiveCamera()->getRotation();

	int oldCamera = g->getActiveCameraIndex();
	//g->cleanEditorsSceneObjects();
	
	m_SaveLoadProgressDraw = true;
	m_SaveLoadProgress = 0;
			
	//s32 size = 65536;
	//void* memory = new c8[size];

	//CMemoryWriteFile* file = new CMemoryWriteFile(memory, size, m_SceneFileName.c_str(), true);

	IXMLWriter* xml;

	if(!bAutoSave)
	{
		xml = g->device->getFileSystem()->createXMLWriter(m_SceneFileName.c_str());
	}
	else
	{
		xml = g->device->getFileSystem()->createXMLWriter((m_SceneFileName + ".autosave").c_str());
	}
		
	if (!xml)
		return;
	int start = g->device->getTimer()->getRealTime();

	io::IAttributes* attr = g->device->getFileSystem()->createEmptyAttributes();

	xml->writeXMLHeader();
	xml->writeLineBreak();
	
	xml->writeElement(L"irr_scene", false);
	xml->writeLineBreak();
	xml->writeLineBreak();
	
		xml->writeElement(L"irr_version", false);
		xml->writeLineBreak();
		attr->addInt("Major" , g->m_versionMajor);
		attr->addInt("Minor" , g->m_versionMinor);
		attr->addInt("Build" , g->m_versionBuild);
		attr->write(xml);
		attr->clear();
		xml->writeClosingTag(L"irr_version");
		xml->writeLineBreak();
		xml->writeLineBreak();

		time_t timer = time(NULL);
		u32 t = timer;

		//xml->writeElement(L"irr_file_time", true, L"timer", stringw(t).c_str());
		//xml->writeLineBreak();
		//xml->writeLineBreak();

		//xml->writeElement(L"irr_obj_count", true, L"count", stringw(m_SceneObjects.size()).c_str());
		//xml->writeLineBreak();
		//xml->writeLineBreak();

		for(int i=0;i<m_stringsFiles.size();i++)
		{
			xml->writeElement(L"irr_strings", true, L"file", stringw(m_stringsFiles[i].c_str()).c_str());
			xml->writeLineBreak();
		}		
		xml->writeLineBreak();

		xml->writeElement(L"irr_music", true, L"file", stringw(m_musicFile.c_str()).c_str());
		xml->writeLineBreak();
		xml->writeLineBreak();

	TreeNode* treeNode = ui->m_sceneGraphTree->GetRootNode();
	saveTreeNode(treeNode, xml, bAutoSave);
	
	//for (u32 i = 0; i < m_SceneObjects.size(); i ++)
	//{
	//	saveSceneObject(m_SceneObjects[i], xml);
	//}

	xml->writeElement(L"irr_camera");
	xml->writeLineBreak();
	
	//m_SceneObjects[i]->m_SceneNode->serializeAttributes(attr);

	attr->addInt("type", oldCamera);
	attr->addVector3d("Position", cpos);
	attr->addVector3d("Target", tpos);
	//attr->addQuaternion("Rotation", m_SceneObjects[i]->m_SceneNode->getRotation());
	//attr->addVector3d("Scale", m_SceneObjects[i]->m_SceneNode->getScale());
	//attr->addBool("Visible", m_SceneObjects[i]->m_SceneNode->isVisible());

	if (attr->getAttributeCount() != 0)
	{
		attr->write(xml);
		//xml->writeLineBreak();
	}
	
	attr->drop();
	xml->writeClosingTag(L"irr_camera");
	xml->writeLineBreak();
	xml->writeClosingTag(L"irr_scene");
	xml->writeLineBreak();

	
	xml->drop();
	//file->drop();

	int end = g->device->getTimer()->getRealTime();
	DEBUG_OUT("Save took %d \n" , (end - start));

	m_SaveLoadProgressDraw = false;

	//g->initScene();
	//g->setActiveCamera(oldCamera);
	//g->sceneManager->getActiveCamera()->setPosition(cpos);
	//g->sceneManager->getActiveCamera()->setTarget(tpos);

	//if(oldCamera == CAMERA_XY)
	//{
	//	CPlaneCameraAnimator* anim =
	//		(CPlaneCameraAnimator*)*g->sceneManager->getActiveCamera()->getAnimators().begin();

	//	anim->setZoom();
	//}

	//g->sceneManager->getActiveCamera()->setScale(cscale);
	//g->sceneManager->getActiveCamera()->setRotation(crot);

	m_bModified = false;

	if(!bAutoSave)
	{
		DeleteAutoSave();
	}

	//save collision file
	//if(!bAutoSave)
	//{
	//	IWriteFile* pFile = g->device->getFileSystem()->createAndWriteFile((m_SceneFileName + ".col").c_str());

	//	u32 triCount = 0;
	//	for (u32 i = 0; i < m_SceneObjects.size(); i++)
	//	{
	//		if (m_SceneObjects[i]->m_UserData->getAttributeAsString("!GameType") == "Collisions")
	//		{
	//			IMeshSceneNode*	collisionMeshNode = GetColladaMeshFromVisualScene(m_SceneObjects[i]->m_SceneNode);
	//			IMesh* pMesh = collisionMeshNode->getMesh();
	//			u32 bufferCount = pMesh->getMeshBufferCount();

	//			for (u32 k=0; k < bufferCount; k++)
	//			{
	//				IMeshBuffer* pMeshBuffer = pMesh->getMeshBuffer(k);
	//				u32 indexCount = pMeshBuffer->getIndexCount();
	//				triCount += indexCount/3;
	//			}

	//			break;
	//		}
	//	}

	//	pFile->write(&triCount, sizeof(u32));

	//	for (u32 i = 0; i < m_SceneObjects.size(); i++)
	//	{
	//		if (m_SceneObjects[i]->m_UserData->getAttributeAsString("!GameType") == "Collisions")
	//		{
	//			WriteToCollisionFile(pFile, m_SceneObjects[i]->m_SceneNode);
	//			break;
	//		}
	//	}

	//	pFile->drop();
	//}
	
	//save header files for commands 
	if(!bAutoSave)
	{
		
	}

	//launch post_save.bat
	//STARTUPINFO si;
	//PROCESS_INFORMATION pi;
	//memset(&si, 0, sizeof(si)); 
 //   memset(&pi, 0, sizeof(pi)); 
	//si.cb = sizeof(si);

	//wchar_t* wcmdLine = new wchar_t[1024];
	//stringc cmd = m_editorPath + "\\post_save.bat \"" + m_SceneFilePath + "\\" + m_SceneFileName + "\"";
	//stringw wCmd = stringw(cmd.c_str());
	//const wchar_t* cmdLine = wCmd.c_str();
	//wcsncpy(wcmdLine, cmdLine, wcslen(cmdLine));

	//if (CreateProcessW(NULL, wcmdLine, NULL, NULL, false, 0, NULL, stringw(m_editorPath.c_str()).c_str(), &si, &pi) != false)
	//{
	//	WaitForSingleObject(pi.hProcess, (5 * 1000));
	//}
	//else
	//{
	//	DEBUG_OUT("post save process failed !!!\n");
	//}

 //   /* Release handles */ 
 //   CloseHandle(pi.hProcess); 
 //   CloseHandle(pi.hThread); 
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void CLevelEditor::WriteToCollisionFile(IWriteFile* pFile, ISceneNode* pNode)
{
	//if (!pNode) return;

	//if(pNode->getType() == ESNT_COLLADA_MESH)
	//{
	//	IMeshSceneNode*	collisionMeshNode = (IMeshSceneNode*)pNode;
	//	IMesh* pMesh = collisionMeshNode->getMesh();
	//	u32 bufferCount = pMesh->getMeshBufferCount();

	//	for (u32 k=0; k < bufferCount; k++)
	//	{
	//		IMeshBuffer* pMeshBuffer = pMesh->getMeshBuffer(k);
	//		u16* pIndices = pMeshBuffer->getIndices();
	//		u32 indexCount = pMeshBuffer->getIndexCount();
	//		float *triPos = new float[indexCount * 3];
	//		for (u32 j=0; j < indexCount; j++)
	//		{
	//			vector3df pos = pMeshBuffer->getPosition(pIndices[j]);
	//			matrix4 mat = pNode->getAbsoluteTransformation();
	//			mat.transformVect(pos);
	//			triPos[j*3] = pos.X;
	//			triPos[j*3 + 1] = pos.Y;
	//			triPos[j*3 + 2] = pos.Z;
	//		}

	//		pFile->write(triPos, sizeof(float) * indexCount * 3);
	//		delete[] triPos;
	//	}
	//}

	//core::list<ISceneNode*>::ConstIterator it = pNode->getChildren().begin();
	//for (; it != pNode->getChildren().end(); ++it)
	//{
	//	WriteToCollisionFile(pFile, (*it));
	//}
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void CLevelEditor::DeleteAutoSave()
{
	//delete autosave
	IFileList* pFileList = g->device->getFileSystem()->createFileList();
	for (u32 i=0; i < pFileList->getFileCount(); i++)
	{
		stringc fileName = pFileList->getFileName(i);
		stringc sceneFileNameNoExt = m_SceneFileName;
		int idx = m_SceneFileName.findLast('.');
		if (idx != -1)
		{
			sceneFileNameNoExt = m_SceneFileName.subString(0, idx);
		}

		idx = fileName.find(".autosave");
		if (idx != -1 && idx == (fileName.size() - 9) && fileName.find(sceneFileNameNoExt.c_str()) == 0)
		{
			stringc fullPath = m_SceneFilePath + "\\" + fileName;
			int t = remove (fullPath.c_str());
		}
	}
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void CLevelEditor::saveRoomLinks(CSceneObject* pObj, io::IAttributes *attr)
{
	if (pObj->m_UserData->getAttributeAsString("!GameType") == "Geometry")
	{
		for (int i=0; i < MAX_ROOM_LINKS; i++)
		{
			stringc name = "LinkNode";
			name += i;
			array<stringw> _link;
			_link.push_back(stringw(pObj->m_roomIDLinks[i]));
			_link.push_back(stringw(pObj->m_linkIndexLinks[i]));
			_link.push_back(stringw(pObj->m_linkDoorID[i]));
			attr->addArray(name.c_str(), _link);
		}
	}
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void CLevelEditor::loadRoomLinks(CSceneObject* pObj, io::IAttributes *attr)
{
	if (pObj->m_UserData->getAttributeAsString("!GameType") == "Geometry")
	{
		for (int i=0; i < MAX_ROOM_LINKS; i++)
		{
			stringc name = "LinkNode";
			name += i;
			array<stringw> _link;

			if (attr->existsAttribute(name.c_str()))
			{
				_link = attr->getAttributeAsArray(name.c_str());

				pObj->m_roomIDLinks[i] = _wtoi(_link[0].c_str());
				pObj->m_linkIndexLinks[i] = _wtoi(_link[1].c_str());
				pObj->m_linkDoorID[i] = _wtoi(_link[2].c_str());
			}
		}
	}
}
